/* 
    联想建议
 */
<template>
    <div class="searchSuggestionMain">
        <van-cell v-for="(item, index) in suggestionsList" :key="index" icon="search" clickable
            @click="$emit('search', item.content)">
            <div slot="title" v-html="heightlight(item.content)"></div>
        </van-cell>

        <!-- {{}}绑定=>纯文本Hello <span style="color:red">World</span> -->
        <!-- <div>{{ htmlStr }}</div> -->

        <!-- v-html指令 -->
        <!-- <div v-html="htmlStr"></div> -->
    </div>
</template>

<script>
import { debounce } from 'lodash' //js工具类,按需加载

export default {
    name: 'SearchSuggestion',
    props: {
        searchText: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            suggestionsList: [],
            htmlStr: 'Hello <span style="color:red">World</span>'
        }
    },
    watch: {
        searchText: {
            // 当searchText发生改变,调用handler函数(名称固定)
            // handler(value) {
            //     this.getSearchSuggestionsList(value)
            // },
            /* 
                优化防抖

                debounce函数:
                    参数一:一个函数
                    参数二:延迟时间,单位毫秒
                    返回值:防抖之后的函数
            */
            handler: debounce(function (value) {
                this.getSearchSuggestionsList(value)
            }, 200),
            immediate: true, //侦听之后立即被调用
        }
    },
    created() {

    },
    methods: {
        // 获取联想推荐列表
        async getSearchSuggestionsList(value) {
            try {
                // const  {res}=await  getSearchSuggestions(value)
                this.suggestionsList = [
                    { content: '1' },
                    { content: '2' },
                    { content: '3' },
                    { content: '4' },
                    { content: '51111' },
                ]
                console.log(value)
            } catch (error) {
                this.$toast('数据获取失败,请稍后重试')
            }
        },
        // 高亮函数
        heightlight(text) {
            // 动态变量创建正则
            /* 
                RegExp正则构造函数
                    参数一:匹配模式字符串
                    参数二:匹配模式,gi全局忽略大小写
            */
            const reg = new RegExp(this.searchText, 'gi')
            return text.replace(reg, `<span class="active">${this.searchText}</span>`)
        },
    }
}
</script>

<style scoped lang="less">
.searchSuggestionMain {
    width: 100%;
    height: 100%;

    /deep/ span.active {
        color: #3296fa !important;
    }
}
</style>